#!/usr/bin/env python3
"""
nodejs-clean-css MCP Server

面向 nodejs-clean-css 命令行工具的 MCP 服务器，提供 CSS 压缩和优化功能。

MCP tools 列表：
1. cleancss_help_version - 获取帮助信息和版本信息
   参数：无
   返回：包含帮助或版本信息的统一 JSON 结构

2. cleancss_basic_optimization - 基本 CSS 压缩优化
   参数：files (List[str]), keep_line_breaks (bool), compatibility (str)
   返回：压缩结果的统一 JSON 结构

3. cleancss_debug_output - 调试模式和输出文件
   参数：files (List[str]), debug (bool), output_file (str)
   返回：调试信息或输出结果的统一 JSON 结构

4. cleancss_import_handling - 处理 CSS 导入
   参数：files (List[str]), root (str), skip_import (bool)
   返回：处理导入后的统一 JSON 结构

5. cleancss_advanced_options - 高级优化选项
   参数：files (List[str]), timeout (int), rounding_precision (int), semantic_merging (bool)
   返回：高级优化结果的统一 JSON 结构

6. cleancss_skip_options - 跳过特定优化步骤
   参数：files (List[str]), skip_advanced (bool), skip_aggressive_merging (bool), skip_media_merging (bool), skip_rebase (bool), skip_restructuring (bool), skip_shorthand_compacting (bool)
   返回：跳过优化后的统一 JSON 结构

7. cleancss_source_map - 生成源映射
   参数：files (List[str]), output_file (str), source_map_inline_sources (bool)
   返回：生成源映射结果的统一 JSON 结构
"""

import subprocess
import json
from typing import List, Optional
from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("NodeJS Clean CSS MCP Server")

@mcp.tool()
def cleancss_help_version() -> dict:
    """
    获取 cleancss 的帮助信息和版本信息
    
    返回：
        dict: 统一 JSON 结构，包含命令执行结果
    """
    commands = [
        ["cleancss", "-h"],
        ["cleancss", "--help"], 
        ["cleancss", "-v"],
        ["cleancss", "--version"]
    ]
    
    results = []
    for cmd in commands:
        try:
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
            results.append({
                "success": result.returncode == 0,
                "command": " ".join(cmd),
                "exit_code": result.returncode,
                "stdout": result.stdout,
                "stderr": result.stderr
            })
        except Exception as e:
            results.append({
                "success": False,
                "command": " ".join(cmd),
                "exit_code": -1,
                "stdout": "",
                "stderr": str(e)
            })
    
    return {
        "success": all(r["success"] for r in results),
        "commands": results
    }

@mcp.tool()
def cleancss_basic_optimization(files: List[str], keep_line_breaks: bool = False, compatibility: Optional[str] = None) -> dict:
    """
    基本 CSS 压缩优化
    
    参数：
        files: CSS 文件路径列表
        keep_line_breaks: 是否保留换行符
        compatibility: 兼容性设置字符串
    
    返回：
        dict: 统一 JSON 结构，包含压缩结果
    """
    cmd = ["cleancss"]
    
    if keep_line_breaks:
        cmd.append("--keep-line-breaks")
    
    if compatibility:
        cmd.extend(["--compatibility", compatibility])
    
    cmd.extend(files)
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def cleancss_debug_output(files: List[str], debug: bool = False, output_file: Optional[str] = None) -> dict:
    """
    调试模式和输出文件功能
    
    参数：
        files: CSS 文件路径列表
        debug: 是否启用调试模式
        output_file: 输出文件路径（可选）
    
    返回：
        dict: 统一 JSON 结构，包含调试信息或输出结果
    """
    cmd = ["cleancss"]
    
    if debug:
        cmd.append("--debug")
    
    if output_file:
        cmd.extend(["--output", output_file])
    
    cmd.extend(files)
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def cleancss_import_handling(files: List[str], root: Optional[str] = None, skip_import: bool = False) -> dict:
    """
    处理 CSS 导入相关功能
    
    参数：
        files: CSS 文件路径列表
        root: 根目录路径
        skip_import: 是否跳过导入处理
    
    返回：
        dict: 统一 JSON 结构，包含处理导入后的结果
    """
    cmd = ["cleancss"]
    
    if root:
        cmd.extend(["--root", root])
    
    if skip_import:
        cmd.append("--skip-import")
    
    cmd.extend(files)
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def cleancss_advanced_options(files: List[str], timeout: Optional[int] = None, rounding_precision: Optional[int] = None, semantic_merging: bool = False) -> dict:
    """
    高级优化选项
    
    参数：
        files: CSS 文件路径列表
        timeout: 超时时间（秒）
        rounding_precision: 舍入精度
        semantic_merging: 是否启用语义合并
    
    返回：
        dict: 统一 JSON 结构，包含高级优化结果
    """
    cmd = ["cleancss"]
    
    if timeout:
        cmd.extend(["--timeout", str(timeout)])
    
    if rounding_precision:
        cmd.extend(["--rounding-precision", str(rounding_precision)])
    
    if semantic_merging:
        cmd.append("--semantic-merging")
    
    cmd.extend(files)
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def cleancss_skip_options(files: List[str], skip_advanced: bool = False, skip_aggressive_merging: bool = False, skip_media_merging: bool = False, skip_rebase: bool = False, skip_restructuring: bool = False, skip_shorthand_compacting: bool = False) -> dict:
    """
    跳过特定优化步骤
    
    参数：
        files: CSS 文件路径列表
        skip_advanced: 是否跳过高级优化
        skip_aggressive_merging: 是否跳过激进合并
        skip_media_merging: 是否跳过媒体查询合并
        skip_rebase: 是否跳过重定位
        skip_restructuring: 是否跳过重构
        skip_shorthand_compacting: 是否跳过简写压缩
    
    返回：
        dict: 统一 JSON 结构，包含跳过优化后的结果
    """
    cmd = ["cleancss"]
    
    if skip_advanced:
        cmd.append("--skip-advanced")
    
    if skip_aggressive_merging:
        cmd.append("--skip-aggressive-merging")
    
    if skip_media_merging:
        cmd.append("--skip-media-merging")
    
    if skip_rebase:
        cmd.append("--skip-rebase")
    
    if skip_restructuring:
        cmd.append("--skip-restructuring")
    
    if skip_shorthand_compacting:
        cmd.append("--skip-shorthand-compacting")
    
    cmd.extend(files)
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def cleancss_source_map(files: List[str], output_file: str, source_map_inline_sources: bool = False) -> dict:
    """
    生成源映射
    
    参数：
        files: CSS 文件路径列表
        output_file: 输出文件路径
        source_map_inline_sources: 是否内联源文件内容
    
    返回：
        dict: 统一 JSON 结构，包含生成源映射的结果
    """
    cmd = ["cleancss", "--source-map"]
    
    if source_map_inline_sources:
        cmd.append("--source-map-inline-sources")
    
    cmd.extend(["--output", output_file])
    cmd.extend(files)
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
        return {
            "success": result.returncode == 0,
            "command": " ".join(cmd),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(cmd),
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

if __name__ == "__main__":
    mcp.run()